﻿#include <QNetworkDatagram>
#include <QJsonObject>
#include <QJsonDocument>
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    //服务端
    m_pServerUdpSocket = new QUdpSocket();

    //客户端
    m_pClientUdpSocket = new QUdpSocket();
    connect(m_pClientUdpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dataReceived()
{
    //收到数据
    while (m_pClientUdpSocket->hasPendingDatagrams()) {
        QNetworkDatagram datagram = m_pClientUdpSocket->receiveDatagram();
        qDebug() << QString(datagram.data());
    }
}

void Widget::on_btnSend_clicked()
{
    QString strIp = ui->lineeditIp->text();
    //quint16 iPort = ui->lineeditPort->text().toUShort();

    if (strIp.isEmpty() || ui->lineeditPort->text().isEmpty()) {
        return;
    }
    QString strSendMsg = ui->texteditSend->toPlainText();

    qDebug() << m_pClientUdpSocket->state();
    m_pClientUdpSocket->connectToHost("42.192.22.128", 8888);
    qDebug() << m_pClientUdpSocket->state();


    /*
    构建一个json格式
{
    MessageType:"Login",
    Account:"gaoyuelong",
    Password:"gaoyuelong"
}
    */
    QJsonObject jsonobj;
    jsonobj.insert("MessageType", "Login");
    jsonobj.insert("Account","admin");
    jsonobj.insert("Password","admin");
    qDebug() << jsonobj << endl;

    strSendMsg = QString(QJsonDocument(jsonobj).toJson(QJsonDocument::Compact));
    qDebug() << strSendMsg;
    //strSendMsg
    QByteArray ba;
    ba.append(strSendMsg);
    const char *c = ba.data();
    qDebug() << m_pClientUdpSocket->write(c, ba.size() + 1);
    //qDebug() << m_pClientUdpSocket->writeDatagram(strSendMsg.toUtf8());
}

void Widget::on_btnListen_clicked()
{
//    if (ui->lineeditListenPort->text().isEmpty()) {
//        return;
//    }
//    quint16 iPort = ui->lineeditListenPort->text().toUShort();
//    m_pServerUdpSocket->bind(QHostAddress::LocalHost, iPort);
//    connect(m_pServerUdpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
}
